package models

import (
	"os"
    "net"
	"fmt"
	"log"
	"time"
	"strconv"
	//"errors"
	//"reflect"
	//"strings"
	"github.com/astaxie/beego/orm"
)

// 与数据库log表映射的结构体
type ApiLog struct {
	Id          int       `orm:"column(id);auto"`
	CreateDate  time.Time `orm:"column(create_date);type(datetime)"`
	Explain     string    `orm:"column(explain);size(255)"`
	Ip     		string    `orm:"column(ip);size(50)"`
	ApiUrl		string    `orm:"column(api_url);size(100)"`
}

type AddApiLogStruct struct {
	Id          int64     `auto:"true" primary_key:"true" json:"id"`
	Explain     string    `json:"explain"`
	CreateDate  string    `json:"create_date"`
	Ip 		    string    `json:"ip"`
	ApiUrl      string    `json:"api_url"`
}

func (t *ApiLog) TableName() string {
	return "too_api_log"
}

// 执行main方法
func main() {

	dbObj := orm.NewOrm()  // 实例化数据库操作对象
	
    //通过事务方式来进行数据插入
	err := dbObj.Begin()
	sql := fmt.Sprintf("insert into too_api_log(CreateDate, Explain, Ip)"+
		" values ('%s','调用接口','169.254.119.242')", "2017-10-10 15:13:12")
	_, err = dbObj.Raw(sql).Exec()
	if err != nil {
		dbObj.Rollback()
		fmt.Println("插入too_api_log表出错,事务回滚")
	} else {
		dbObj.Commit()
		fmt.Println("插入too_api_log表成功,事务提交")
	}
    // 查询数据库
	apilog := make([]ApiLog, 20)

	sql = "select Id,CreateDate,Explain,Ip from too_api_log"
	fmt.Println(sql)
	num, er := dbObj.Raw(sql).QueryRows(&apilog)
	if er != nil {
		fmt.Println("查询log信息出错")
	} else {
		fmt.Printf("从too_api_log表中共查询到记录:%d条\n", num)
		for index, _ := range apilog {
			fmt.Printf("第%d个log信息：", index+1)
			fmt.Printf("创建时间：%s,调用说明:%s，调用IP:%s", apilog[index].CreateDate, apilog[index].Explain, apilog[index].Ip)
		}
	}
}

// 新增记录接口
func (this *AddApiLogStruct) ApiLogSave() (applog map[string]string, code int, err error) {

	dbObj := orm.NewOrm()  // 实例化数据库操作对象
	
	sql_str := fmt.Sprintf("INSERT INTO %s (`explain`,`create_date`,`ip`,`api_url`) VALUES ('%s','%s','%s','%s')", "too_api_log", this.Explain, this.CreateDate, this.Ip, this.ApiUrl)
	//log.Printf(sql_str)

	result, err := dbObj.Raw(sql_str).Exec()
	if err != nil {
		log.Println("插入数据至：too_api_log出错")
	}

	// 获取自增id
	id, err := result.LastInsertId()
	if err != nil {
		log.Println("applog insert get id failed",err)
	}

	log.Println("applog insert succ", id)

	applog, _, _ = GetApiLogItemById(id)

	return
}

// 获取单条记录接口
func GetApiLogItemById(id int64) (applog map[string]string, code int, err error) {

	dbObj := orm.NewOrm()  // 实例化数据库操作对象
	
	sql := fmt.Sprintf("select `id`,`create_date`,`explain`,`ip`,`api_url` from %s where id=%d", "too_api_log", id)
	log.Printf(sql)

	//查询数据库
	applogs := make([]ApiLog,20)
	result := make(map[string]string)

	num, er := dbObj.Raw(sql).QueryRows(&applogs)

	if er != nil {
		log.Println("查询log信息出错")
	} else {
		log.Printf("从too_api_log表中共查询到记录:%d条\n", num)
		for index, _ := range applogs {
			//applog["id"] = strconv.FormatInt(int64,applogs[index].Id)
			result["id"] = strconv.Itoa(applogs[index].Id)
			result["explain"] = applogs[index].Explain
			result["createDate"] = applogs[index].CreateDate.Format("2006-01-02 15:04:05")
			result["ip"] = applogs[index].Ip
			result["apiUrl"] = applogs[index].ApiUrl
			log.Printf("第%d个log信息", index+1)
			log.Printf("logId：%d,创建时间:%s，说明:%s,IP信息:%s,api地址:%s", applogs[index].Id, applogs[index].CreateDate, applogs[index].Explain, applogs[index].Ip, applogs[index].ApiUrl)
		}
	}

	applog = result

	return 
}

/**
 * 获取ip信息
 */
func GetIps() (ips string, err error) {

    addrs, err := net.InterfaceAddrs()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    for _, address := range addrs {
        // 检查ip地址判断是否回环地址
        if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
            if ipnet.IP.To4() != nil {
                fmt.Println(ipnet.IP.String())
                ips = ipnet.IP.String()
            }
        }
    }
    return
}
